package behavior_analysis_model;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import behavior_analysis_control.DialogErrorException;
import behavior_analysis_control.POIFinder;
import behavior_analysis_control.POINotFoundException;
import behavior_analysis_control.TrackUtils;


/**
 *  FileIO is the class used to save persistent data for the Urban
 *  Parks application. 
 * @author Craig Markham
 * @version 11-10-12
 */

public class MapGenerator {

	public static final String APIKEY = "AIzaSyCzSnEuWgf3LNXrhjObnnXH6hOPQRFOqL8";
	
	/**
	 * The relative File Path for the file.
	 */
	private static String my_path;
	
	/**
	 * The File name for the User data.
	 */
	private static String my_UsersData;
	
	/**
	 * Default Constructor for FileManager.
	 */
	public MapGenerator(){
		my_path = ".";
		my_UsersData = "UserLocation.html";
	}
	
	/**
	 * Constructor for FileManager.
	 * @param the_path The relative path for the data files.

	 * @Pre Parameter must not be null,
	 */
	public MapGenerator(String the_path){
		my_path = the_path;
		my_UsersData = "UserLocation2.html";
	}
	
	
	/**
	 * Writes the java script to be saved to data file.
	 * @param tracks 
	 * 
	 * @param the_Track The list of Tracks from the data file.
	 * @throws POINotFoundException 
	 */	
	public void createFile(final POIFinder the_pf) throws DialogErrorException {
		//int num_POIs = set.size();
		final StringBuilder errors = new StringBuilder();
		try {
			FileWriter outFile = new FileWriter(my_path.concat(my_UsersData));
			PrintWriter out = new PrintWriter(outFile);

			// Header for HTML File
			out.println("<!DOCTYPE html><html><head><meta name=\"viewport\" content=\"initial-scale=1.0, user-scalable=no\" />");
			out.println("<style type=\"text/css\"> html{height: 100%} body{height:100%; margin:0; padding:0} #map_canvas{height:100%}</style>");
			out.println("<script type=\"text/javascript\" src=\"https://maps.googleapis.com/maps/api/js?key=" + APIKEY + "&sensor=true\"></script>");
			out.print("<script type=\"text/javascript\"> \nfunction initialize() {");
			//create variables for 
			out.println("\nvar home = 'http://files.softicons.com/download/toolbar-icons/super-mono-3d-icons-by-double-j-design/png/64x64/home.png';");
			out.println("var work = 'http://files.softicons.com/download/toolbar-icons/super-mono-3d-icons-by-double-j-design/png/64x64/briefcase.png';");
			out.println("var shopping = 'http://files.softicons.com/download/toolbar-icons/super-mono-3d-icons-by-double-j-design/png/64x64/shopping-cart.png';");
			out.println("var pin = 'http://files.softicons.com/download/toolbar-icons/super-mono-3d-icons-by-double-j-design/png/64x64/pin.png';");
			
			//  Create a new viewpoint bound
			out.println("//  Create a new viewpoint bound");
			out.println("var bounds = new google.maps.LatLngBounds();");
			
			//create the map, centered TODO: decide where to center
			out.println("var mapOptions = {center: homeLatLng, zoom: 4, mapTypeId: google.maps.MapTypeId.ROADMAP};");
			out.println("var map = new google.maps.Map(document.getElementById(\"map_canvas\"), mapOptions);");
			
			//create the variables for each track to display
			try {
				final Track home = the_pf.getHome();
				out.print("var homeLatLng = new google.maps.LatLng(");
				out.println(home.getLatitude() + "," + home.getLongitude() + "); ");
				out.println("bounds.extend(homeLatLng);" );
				//add the markers
				StringBuilder sb = new StringBuilder();
				sb.append("Home:");
				sb.append("\\n");
				try {
					sb.append(TrackUtils.getAddress(home));
					sb.append("\\n");
				} catch (final POINotFoundException p) {
					//append nothing
				}
				sb.append(home.latLongToString());
				sb.append("\\n");
				sb.append(home.totalTimeToString());
				sb.append("\\n");
				out.println("var homeMarker = new google.maps.Marker({position: homeLatLng, map:map, icon:home, title:\"" + sb.toString() + "\"}); ");
				out.println(" ");
			} catch (final POINotFoundException p) {
				errors.append(p.getMessage() + "\n");
			}
			
			try {
				final Track work = the_pf.getWork();
				out.print("var workLatLng = new google.maps.LatLng(");
				out.println(work.getLatitude() + "," + work.getLongitude() + "); ");
				out.println("bounds.extend(workLatLng);" );
				//add the markers
				StringBuilder sb = new StringBuilder();
				sb.append("Work:");
				sb.append("\\n");
				try {
					sb.append(TrackUtils.getBusinessName(work));
					sb.append("\\n");
				} catch (final POINotFoundException p) {
					//append nothing
				}
				try {
					sb.append(TrackUtils.getAddress(work));
					sb.append("\\n");
				} catch (final POINotFoundException p) {
					//append nothing
				}
				sb.append(work.latLongToString());
				sb.append("\\n");
				sb.append(work.totalTimeToString());
				sb.append("\\n");
				out.println("var workMarker = new google.maps.Marker({position: workLatLng, map:map, icon:work, title:\"" + sb.toString() + "\"}); ");
				out.println(" ");
			} catch (final POINotFoundException p) {
				errors.append(p.getMessage() + "\n");
			}

			for (int i = 0; i < POIFinder.NUM_POIS; i++) {
				try {
					final Track poi = the_pf.getPOI(i);
					out.print("var poiLatLng" + i + " = new google.maps.LatLng(");
					out.println(poi.getLatitude() + "," + poi.getLongitude() + "); ");
					out.println("bounds.extend(poiLatLng" + i + ");" );
					//add the markers
					StringBuilder sb = new StringBuilder();
					sb.append("POI ");
					sb.append("#");
					sb.append(i + 1);
					sb.append("\\n");
					try {
						sb.append(TrackUtils.getBusinessName(poi));
						sb.append("\\n");
					} catch (final POINotFoundException p) {
						//append nothing
					}
					
					try {
						sb.append(TrackUtils.getAddress(poi));
						sb.append("\\n");
					} catch (final POINotFoundException p) {
						//append nothing
					}
					sb.append(poi.latLongToString());
					sb.append("\\n");
					sb.append(poi.totalTimeToString());
					sb.append("\\n");
					out.println("var poiMarker" + i + " = new google.maps.Marker({position: poiLatLng" + i + ", map:map, icon:pin, title:\"" + sb.toString() + "\"}); ");
					out.println(" ");
				} catch (final POINotFoundException p) {
					errors.append(p.getMessage() + "\n");
				}
			}
			
			
			//  Fit these bounds to the map
			out.println("//  Fit these bounds to the map" );
			out.println("map.fitBounds(bounds);" );
			
			//file footer
			out.println("}</script></head><body onload=\"initialize()\"><div id=\"map_canvas\" style=\"width:100%; height:100%\"></div></body></html>");
			out.close();
		} catch (final IOException e){
			errors.append(e.getMessage() + "\n");
		}
		if (!errors.toString().isEmpty()) {
			throw new DialogErrorException(errors.toString());
		}
	}
	
	public void openURI() {
        
		if( !java.awt.Desktop.isDesktopSupported() ) {
            System.err.println( "Desktop is not supported (fatal)" );
            System.exit( 1 );
        }
        
        java.awt.Desktop desktop = java.awt.Desktop.getDesktop();
        if( !desktop.isSupported( java.awt.Desktop.Action.BROWSE ) ) {
            System.err.println( "Desktop doesn't support the browse action (fatal)" );
        }

        try {
            java.net.URI uri = new java.net.URI(my_path.concat(my_UsersData));
            desktop.browse( uri );
        }
        catch ( Exception e ) {
            System.err.println( e.getMessage() );
        }
    }
	
}
